package com.example.joewang.repluginmotion.hook;

import android.os.Build;
import android.os.Handler;

import com.example.joewang.repluginmotion.plugin.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class HookUtils {

    public static final String HOOK_ORIGIN_INTENT = "origin_intent";

    public static void hookAm() {
        try {
            Object IActivityManagerInstance = null;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                Class clz = Class.forName("android.app.ActivityManager");
                IActivityManagerInstance= ReflectionUtils.getFieldObject(clz, "IActivityManagerSingleton", null);
            }else{
                Class clz = Class.forName("android.app.ActivityManagerNative");
                IActivityManagerInstance = ReflectionUtils.getFieldObject(clz, "gDefault", null);
            }
            Class clz2 = Class.forName("android.util.Singleton");
            Field instanceField = ReflectionUtils.getField(clz2, "mInstance");
            Object iAmInstance = instanceField.get(IActivityManagerInstance);
            Class<?> iActivityManagerClazz = Class.forName("android.app.IActivityManager");
            Object target = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{iActivityManagerClazz}, new IActivityManagerHook(iAmInstance));
            instanceField.set(IActivityManagerInstance, target);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    public static void hookCallback() {
        try {
            Class clz = Class.forName("android.app.ActivityThread");
            Object ativityThreadInstance = ReflectionUtils.getFieldObject(clz, "sCurrentActivityThread", null);
            Object hInstance = ReflectionUtils.getFieldObject(clz, "mH", ativityThreadInstance);
            ReflectionUtils.setField(Handler.class, "mCallback", hInstance, new HandlerHook((android.os.Handler) hInstance));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
